package com.cn.spring;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class HspApplicationContext {
    private ConcurrentHashMap<String, Object> ioc = new ConcurrentHashMap<>();

    public HspApplicationContext(String iocBeanXmlFile) throws DocumentException,
            ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //得到一个解析器
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File(iocBeanXmlFile));
        //1. 得到rootElement
        Element rootElement = document.getRootElement();
        System.out.println(rootElement.getName());
        //2. 获 取 第1 个bean, 如 有 所 有 ，就 遍 历-老 师 就 是 一 个 示 意
        Element bean = (Element) rootElement.elements("bean").get(0);
        String id = bean.attributeValue("id");
        //class="com.cn.spring.Monster"
        String classFullPath = bean.attributeValue("class");

        //<property name="monsterId" value="10"/>
        //<property name="name" value="蜈蚣精"/>
        //<property name="skill" value="蜇人"/>
        List<Element> property = bean.elements("property");

        Integer monsterId = Integer.parseInt(property.get(0).attributeValue("value"));
        String name = property.get(1).attributeValue("value");
        String skill = property.get(2).attributeValue("value");

        //3. 使 用 反 射 创 建bean 实 例 ，并 放 入 到 ioc 中
        Class cls = Class.forName(classFullPath);

        //Monster instance = (Monster)cls.newInstance();
        Constructor constructor = cls.getConstructor();
        Monster instance = (Monster) constructor.newInstance();
        instance.setMonsterId(monsterId);
        instance.setName(name);
        instance.setSkill(skill);
        ioc.put(id, instance);
    }

    public Object getBean(String id){
        return ioc.get(id);
    }
}
